<template>
  <div class="content">
    <div class="header">
      <el-select
        v-model="listQuery.unitDeptCode"
        clearable
        placeholder="请选择单位"
        class="form-top-p"
        @change="changDept">
        <el-option
          v-for="item in deptList_dw"
          :key="item.deptNo"
          :label="item.deptName"
          :value="item.deptNo" />
      </el-select>
      <el-select v-model="listQuery.lineId" class="form-top-p" clearable placeholder="请选择线路">
        <el-option
          v-for="item in lines"
          :key="item.seclineId"
          :label="item.seclineName"
          :value="item.seclineId" />
      </el-select>
      <el-select
        v-model="listQuery.defectCategoryIdList"
        clearable
        multiple
        placeholder="请选择缺陷分类"
        class="form-top-p">
        <el-option
          v-for="item in defectTypeList"
          :key="item.id"
          :label="item.categoryName"
          :value="item.id" />
      </el-select>

      <el-date-picker
        v-model="times.startYear"
        type="year"
        format="yyyy"
        value-format="yyyy"
        placeholder="选择开始年"
        @change="getYearList" />～
      <el-date-picker
        v-model="times.endYear"
        type="year"
        format="yyyy"
        value-format="yyyy"
        placeholder="选择结束年"
        @change="getYearList" />

      <el-button
        type="primary"
        style="margin-left:15px;"
        size="mini"
        icon="el-icon-search"
        @click="search">查询</el-button>
      <el-button
        style="background: #A7B7C9;color:#FFFFFF;"
        size="mini"
        icon="el-icon-refresh"
        @click="reset">重置</el-button>
    </div>
    <div class="main">
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img src="@/assets/images/line.png" style="margin-right:7px;" alt>
              <span
                style="margin-right:7px;">{{ ' 缺陷年度走势（' + listQuery.yearList[0] + '-' + listQuery.yearList[listQuery.yearList.length - 1] + '）' }}</span>
            </div>

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="getImg1">导出图片</el-button>
          </div>
          <div ref="charts1" class="cardMain" />
        </el-card>
      </div>
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img
                src="@/assets/images/userInspetionCharts.png"
                style="margin-right:7px;"
                alt>
              <span
                style="margin-right:7px;">{{ ' 缺陷按年份堆叠（' + listQuery.yearList[0] + '-' + listQuery.yearList[listQuery.yearList.length - 1] + '）' }}</span>
            </div>

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="getImg2">导出图片</el-button>
          </div>
          <div ref="charts2" class="cardMain" />
        </el-card>
      </div>
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img src="@/assets/images/chrts.png" style="margin-right:7px;" alt>
              <span
                style="margin-right:7px;">{{ ' 缺陷类型百分比（' + listQuery.yearList[0] + '-' + listQuery.yearList[listQuery.yearList.length - 1] + '）' }}</span>
            </div>

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="getImg3">导出图片</el-button>
          </div>
          <div ref="charts3" class="rateCardMain">
            <div
              v-for="(item,index) in rateList"
              :id="'reteCharts' + index"
              :key="index"
              style="width:10%;height:100%;display: inline-block;" />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { findManageUnitDeptList, defectCategoryList, railtypeList, getLineList } from '@/api/platform'
import { defectYearTrend, defectTypeBarAnalyse, defectTypePercent } from '@/api/cms/Analysis-management/synthetical-Analysis/yearDefect'
import html2canvas from 'html2canvas'
import echarts from 'echarts'
export default {
  data() {
    return {
      deptList_dw: [],
      defectTypeList: [],
      railTypes: [],
      lines: [],
      times: {
        startYear: (new Date().getFullYear() - 3).toString(),
        endYear: new Date().getFullYear().toString()
      },
      listQuery: {
        unitDeptCode: '',
        defectCategoryIdList: '',
        yearList: [],
        railType: '',
        lineId: ''
      },
      rateList: [],
      echart2: {
        xData: [],
        yData: [],
        legendData: []

      }
    }
  },
  mounted() {
    this.getList()
    this.getYearList()
  },
  methods: {
    getList() {
      defectCategoryList().then((response) => {
        this.defectTypeList = response.data
      })
      findManageUnitDeptList({}).then(response => {
        var resData = response.data
        for (var i in resData) {
          if (resData[i].deptNo === '001200') {
            resData.splice(i, 1)
          }
        }
        this.deptList_dw = resData
      })
      this.search()
    },
    search() {
      this.getCherts1()
      this.getCherts2()
      this.getCherts3()
    },
    reset() {
      this.listQuery = {
        unitDeptCode: '',
        railType: '',
        lineId: '',
        defectCategoryIdList: '',
        yearList: [(new Date().getFullYear() - 3).toString(), (new Date().getFullYear() - 2).toString(), (new Date().getFullYear() - 1).toString(), new Date().getFullYear().toString()]
      }
      this.search()
    },
    getCherts1() {
      defectYearTrend(this.listQuery).then(res => {
        this.echart2.xData = Object.keys(res.data)
        console.log('echarts.xData', this.echart2.xData)
        const xData = this.listQuery.yearList
        const yData = []
        const legendData = []

        for (const key in res.data) {
          legendData.push(key)
          yData.push({
            name: key,
            data: res.data[key],
            type: 'line'
          })
        }

        const myChart = echarts.init(this.$refs.charts1)
        const options = {
          title: {
            text: this.getDeptName(this.listQuery.unitDeptCode),
            x: 'center',
            y: 10
          },
          tooltip: {
            trigger: 'item'
          },

          xAxis: {
            type: 'category',
            data: xData,
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          legend: {
            type: 'scroll',
            top: '5%',
            right: '5%',
            left: '70%',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 10, // 设置高度
            data: legendData
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '20%',
            top: '25%'
          },

          yAxis: {
            type: 'value',
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          color: ['#3646FA', '#4493FB', '#57E5FD'],
          series: yData
        }
        console.log('options.series', options.series)
        myChart.clear()
        myChart.setOption(options)
      })
    },
    getImg1() {
      const myChart = echarts.init(this.$refs.charts1)
      this.getImage('png', myChart)
    },
    getCherts2() {
      defectTypeBarAnalyse(this.listQuery).then(res => {
        let xData = []
        const yData = []
        const legendData = this.listQuery.yearList
        xData = res.data.typeName

        for (const key in res.data) {
          if (key !== 'typeName') {
            yData.push({
              name: key,
              data: res.data[key],
              type: 'bar',
              barWidth: 20,
              stack: 'zs'
            })
          }
        }
        const myChart = echarts.init(this.$refs.charts2)
        const options = {

          tooltip: {
            trigger: 'item'
          },

          xAxis: {
            nameLocation: 'end', // 坐标轴名称显示位置。

            data: xData,
            axisLabel: {
              interval: 0,
              rotate: '-45',
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          legend: {
            top: '5%',
            right: '5%',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 10, // 设置高度

            data: legendData
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '30%',
            top: '25%'
          },

          yAxis: {
            type: 'value',
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          color: ['#3646FA', '#4493FB', '#57E5FD'],
          series: yData
        }
        myChart.clear()
        myChart.setOption(options)
      })
    },
    getImg2() {
      const myChart = echarts.init(this.$refs.charts2)
      this.getImage('png', myChart)
    },
    getCherts3() {
      defectTypePercent(this.listQuery).then(res => {
        this.rateList = res.data

        setTimeout(() => {
          res.data.forEach((item, index) => {
            const myChart = echarts.init(document.getElementById(`reteCharts${index}`))
            const option = {
              title: {
                text: item.percent + '%',
                textStyle: {
                  color: '#409EFF',
                  fontSize: 18,
                  fontFamily: 'YouSheBiaoTiHei'
                },

                subtext: item.name,
                subtextStyle: {
                  color: '#606266',
                  fontSize: 16
                },

                itemGap: 60,
                left: 'center',
                top: '42%'
              },
              tooltip: {
                formatter: function(params) { }
              },
              angleAxis: {
                max: 100,
                clockwise: false, // 逆时针
                // 隐藏刻度线
                show: false
              },
              radiusAxis: {
                type: 'category',
                show: true,
                axisLabel: {
                  show: false
                },
                axisLine: {
                  show: false
                },
                axisTick: {
                  show: false
                }
              },
              polar: {
                radius: '100%',
                center: ['50%', '50%']
              },
              series: [
                {
                  stack: '测试',
                  type: 'bar',
                  data: [Number(item.percent)],
                  showBackground: true,
                  backgroundStyle: {
                    color: '#EFF2F5'
                  },
                  coordinateSystem: 'polar',
                  roundCap: true,
                  barWidth: 10,
                  silent: true,
                  itemStyle: {
                    normal: {
                      opacity: 1,
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                          offset: 0,
                          color: '#68F6FF'
                        },
                        {
                          offset: 1,
                          color: '#0168FF'
                        }
                      ]),

                      borderWidth: 3
                    }
                  }
                },
                {
                  stack: '测试',
                  type: 'bar',
                  data: [0.01],
                  showBackground: true,
                  backgroundStyle: {
                    color: '#E6EFFB',
                    shadowColor: '#fff',
                    shadowBlur: 10,
                    shadowOffsetY: 2
                  },
                  coordinateSystem: 'polar',
                  roundCap: true,
                  barWidth: 14,
                  itemStyle: {
                    color: '#90BDFF',
                    borderColor: 'rgba(81,143,239, 1)',
                    borderWidth: 3
                  }
                }
              ]
            }
            myChart.setOption(option)
            myChart.resize()
          })
        }, 1000)
      })
    },
    getImg3() {
      console.log(html2canvas)
      // debugger
      html2canvas(this.$refs.charts3).then(canvas => {
        const dataURL = canvas.toDataURL('image/png')
        var $a = document.createElement('a')
        var type = 'png'
        $a.download = 'charts.' + type
        $a.target = '_blank'
        $a.href = dataURL
      })
      // const myChart = echarts.init(this.$refs.charts3)
      // this.getImage('png', myChart)
    },
    getDefectTypeName(id) {
      let name = ''
      this.defectTypeList.forEach(item => {
        if (item.id === id) {
          name = item.categoryName
        }
      })
      return name
    },
    getDeptName(id) {
      let name = ''
      this.deptList_dw.forEach(item => {
        if (item.deptNo === id) {
          name = item.deptName
        }
      })
      return name
    },
    getImage(imgType, myChart) {
      var url = myChart.getConnectedDataURL({
        pixelRatio: 2, // 导出的图片分辨率比率,默认是1
        backgroundColor: '#fff', // 图表背景色
        excludeComponents: [
          // 保存图表时忽略的工具组件,默认忽略工具栏
          'toolbox'
        ],
        type: imgType // 图片类型支持png和jpeg
      })
      var $a = document.createElement('a')
      var type = imgType
      $a.download = 'charts.' + type
      $a.target = '_blank'
      $a.href = url
      // Chrome and Firefox
      if (typeof MouseEvent === 'function') {
        var evt = new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: false
        })
        $a.dispatchEvent(evt)
      } else {
        var base64 = {
          dataURL: url,
          type: imgType,
          ext: imgType
        }
        var blob = this.convertBase64UrlToBlob(base64)
        // 下载
        window.navigator.msSaveBlob(
          blob,
          myChart.getOption().title[0].text + '.' + imgType
        )
      }
    },
    convertBase64UrlToBlob(base64) {
      var parts = base64.dataURL.split(';base64,')
      var contentType = parts[0].split(':')[1]
      var raw = window.atob(parts[1])
      var rawLength = raw.length
      var uInt8Array = new Uint8Array(rawLength)
      for (var i = 0; i < rawLength; i++) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    getYearList() {
      var start = this.times.startYear ? parseInt(this.times.startYear) : (new Date().getFullYear() - 3)
      var end = this.times.endYear ? parseInt(this.times.endYear) : new Date().getFullYear()
      this.listQuery.yearList = []
      for (var i = start; i <= end; i++) {
        this.listQuery.yearList.push(i.toString())
      }
    },
    // 获取线路
    getLineList() {
      getLineList({ railType: this.listQuery.railType, unitDeptCode: this.listQuery.unitDeptCode }).then((response) => {
        this.lines = response.data
      })
    },
    changeRailType(val) {
      this.listQuery.lineId = ''
      this.getLineList()
    },
    changDept(val) {
      this.listQuery.railType = ''
      this.listQuery.lineId = ''
      railtypeList().then(response => {
        this.railTypes = response.data
      })
      this.getLineList()
    }
  }

}
</script>
<style lang="scss" scoped>
.content {
    padding: 0 20px;
    width: 100%;
    height: 100%;
    padding-bottom: 20px;
}
.header {
    width: 100%;
    height: 70px;
    display: flex;
    align-items: center;
}
.form-top-p {
    width: 220px;
    margin-right: 15px;
    margin-bottom: 0;
}
/deep/.el-select__tags {
    max-height: 60px;
    overflow: auto;
}
/deep/.el-input--medium .el-input__inner {
    height: 30px;
    line-height: 30px;
}
/deep/.el-range-editor--medium.el-input__inner {
    height: 30px;
    line-height: 30px;
}
.main {
    height: calc(100% - 70px);
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.main_div {
    height: 32%;
    width: 100%;
}
/deep/.box-card {
    width: 100%;
    height: 100%;
    margin: 0 !important;
    float: none;
    background: #ffffff;
    box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
    border-radius: 6px;
    border: 0;
}
/deep/.el-card__header {
    padding: 0;
    height: 60px;
    padding: 0 20px;
    border: 0;
    box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.06);
    background-color: #fff !important;
}
/deep/.el-card__body {
    padding: 0;
    width: 100%;
    height: calc(100% - 60px);
    border: 0;
}
.cardMain {
    width: 100%;
    height: 100%;
}
.rateCardMain {
    width: 100%;
    height: 100%;

    overflow: auto;
}
</style>
